package com.example.queue09.queue;

/**
 * 循环数组实现队列(浪费一个格子不存)
 * @auther lijiewei
 * @date 2021/8/23 13:41
 */
public class CircularQueue {

    //数组
    private String[] items;
    //队列容量
    private int size = 0;
    //头下标
    private int head = 0;
    //尾下标
    private int tail = 0;

    public CircularQueue(int capacity) {
        if (capacity <= 0) {
            throw new RuntimeException("容量必须大于0");
        }
        //因为会浪费一个位置，这里就多加一个
        items = new String[capacity+1];
        size = capacity+1;
    }

    /**
     * 入队
     * @param item 元素
     * @return
     * @author lijiewei
     * @date   2021/8/23 13:46
     */
    public boolean enqueue(String item) {
        //满队(浪费了一个位置)
        if ((tail+1) % size == head) {
            return false;
        }
        items[tail] = item;
        tail = (tail+1)%size;
        return true;
    }

    /**
     * 出队
     * @return
     * @author lijiewei
     * @date   2021/8/23 13:51
     */
    public String dequeue() {
        //空队
        if (head == tail) {
            return null;
        }
        String ret = items[head];
        head = (head+1)%size;
        return ret;
    }

    /**
     * 打印所有元素
     * @return
     * @author lijiewei
     * @date   2021/8/23 13:59
     */
    public void printAll() {
        for (int i = head; i%size != tail; i=(i+1)%size) {
            System.out.print(items[i] + " ");
        }
        System.out.println();
    }

}
